/*
 * 
 */

package com.memorytech.starchive;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import jp.co.memory_tech.starchive.R;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.memorytech.starchive.dialog.BarcodeConfirmDialogFragment;
import com.memorytech.starchive.dialog.BarcodeSynDialogFragment;
import com.memorytech.starchive.entity.FileInformation;
import com.memorytech.starchive.httpservice.HttpClientHelper;
import com.memorytech.starchive.httpservice.AbstractMap.SimpleEntry;
import com.memorytech.starchive.httpservice.IService.Methods;
import com.memorytech.starchive.interfaceclass.OnAdvancedSearchResultListener;
import com.memorytech.starchive.interfaceclass.OnListProductSelectedListener;
import com.memorytech.starchive.interfaceclass.OnMainActivityListener;
import com.memorytech.starchive.interfaceclass.OnProductDetailListener;

// TODO: Auto-generated Javadoc
/**
 * The Class ShowDetailActivity.
 * 
 * @author Tam-LT
 */
public class SearchActivity extends FragmentActivity
        implements OnListProductSelectedListener, OnClickListener, Observer,
        OnAdvancedSearchResultListener, OnProductDetailListener {
    private EditText search_field;
    private HttpClientHelper httpClientHelper;

    /**
     * Called when the activity is first created.
     * 
     * @param savedInstanceState the saved instance state
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_product);
        search_field = (EditText) findViewById(R.id.search_field);
        findViewById(R.id.search).setOnClickListener(this);
        findViewById(R.id.advanced_search).setOnClickListener(this);
        TextView textView = (TextView) findViewById(R.id.title);
        textView.setText(getString(R.string.search));

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first
        // fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create an instance of ListProduct
            ListProduct firstFragment = new ListProduct();

            // In case this activity was started with special instructions from
            // an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
        httpClientHelper = HttpClientHelper.getInstance();
    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onPause()
     */
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        httpClientHelper.deleteObserver(this);
    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onResume()
     */
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        httpClientHelper.addObserver(this);
    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Log.i("tamle", "back pressed");
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.detail_fragment);
        if (fragment instanceof AdvancedSearch) {
            findViewById(R.id.list_product_fragment).setVisibility(View.VISIBLE);
            findViewById(R.id.search_bar).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.title)).setText(getString(R.string.search));
        }
        super.onBackPressed();
    }

    /*
     * (non-Javadoc)
     * @see com.arisvn.barcode.ListProduct.OnListProductSelectedListener#
     * onListProductSelected(int)
     */
    @Override
    public void onListProductSelected(FileInformation fileInformation) {
        // TODO Auto-generated method stub

        // Capture the ProductDetail fragment from the activity layout
        ProductDetail productDetail = (ProductDetail)
                getSupportFragmentManager().findFragmentById(R.id.detail_fragment);

        if (productDetail != null) {
            // If ProductDetail frag is available, we're in two-pane layout...

            productDetail.updateProductDetail(fileInformation);

        } else {
            // If the frag is not available, we're in the one-pane layout and
            // must swap frags...

            // Create fragment and give it an argument for the selected
            // Product
            ProductDetail newFragment = new ProductDetail();
            Bundle args = new Bundle();
            args.putSerializable(ProductDetail.FILEINFOMATION, fileInformation);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this
            // fragment,
            // and add the transaction to the back stack so the user can
            // navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }

    }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.search:
                if (search_field.getText().toString().trim().equals("")) {
                    BarcodeConfirmDialogFragment.show(this,
                            "Search field is empty. Please enter barcode before submit");
                } else {
                    Log.i("Tamle", "onClick  R.id.search");
                    // httpClientHelper.addObserver(this);
                    // httpClientHelper.search("");
                    // BarcodeSynDialogFragment.show(this,
                    // "Loading data from server");
                    ListProduct listProduct = (ListProduct)
                            getSupportFragmentManager()
                                    .findFragmentById(R.id.list_product_fragment);

                    if (listProduct != null) {
                        // If ProductDetail frag is available, we're in two-pane
                        // layout...

                        listProduct.updateData();

                    }
                }

                break;
            case R.id.advanced_search:
                ProductDetail productDetail = (ProductDetail)
                        getSupportFragmentManager().findFragmentById(R.id.detail_fragment);

                if (productDetail != null) {

                    findViewById(R.id.list_product_fragment).setVisibility(View.GONE);
                    findViewById(R.id.search_bar).setVisibility(View.GONE);
                    ((TextView) findViewById(R.id.title))
                            .setText(getString(R.string.advanced_search));

                    AdvancedSearch newFragment = new AdvancedSearch();

                    FragmentTransaction transaction = getSupportFragmentManager()
                            .beginTransaction();

                    // navigate back
                    transaction.replace(R.id.detail_fragment, newFragment);
                    transaction.addToBackStack(null);

                    // Commit the transaction
                    transaction.commit();
                }
                break;
            default:
                break;
        }

    }

    /*
     * (non-Javadoc)
     * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        Log.i("Tamle", "update called");
        if (observable instanceof HttpClientHelper) {

            @SuppressWarnings("unchecked")
            SimpleEntry<Methods, List<Object>> ret = (SimpleEntry<Methods, List<Object>>) data;
            // loading.hide();
            // BarcodeSynDialogFragment.dismiss(this);
            switch (ret.getKey()) {
                case search:
                    Log.i("Tamle", "search update called");
                    httpClientHelper.deleteObserver(this);
                    if (ret.getValue() == null || ret.getValue().size() == 0) {

                        Log.i("Tamle", "can't search on server or there are that product");

                    } else {

                        Log.i("Tamle", " search on server successfully");
                    }
                    break;
                case advancedSearch:
                    Log.i("Tamle", "advancedSearch update called");

                    httpClientHelper.deleteObserver(this);

                    break;

                default:
                    break;
            }

        }
    }

    /*
     * (non-Javadoc)
     * @see
     * com.arisvn.barcode.AdvancedSearch.OnAdvancedSearchResult#onSearchResult
     * (java.util.List)
     */
    @Override
    public void onSearchResult(List<Object> result) {
        // TODO Auto-generated method stub
        Log.i("Tamle", "advanced search has result");
        onBackPressed();

        ListProduct listProduct = (ListProduct)
                getSupportFragmentManager()
                        .findFragmentById(R.id.list_product_fragment);

        if (listProduct != null) {
            // If ProductDetail frag is available, we're in two-pane
            // layout...

            listProduct.updateData();

        }
    }

    public void search(String data) {
        // TODO Auto-generated method stub
        Log.i("Tamle", "Search all file with barcode: " + data);
        search_field.setText(data);
        ListProduct listProduct = (ListProduct)
                getSupportFragmentManager()
                        .findFragmentById(R.id.list_product_fragment);

        if (listProduct != null) {
            // If ProductDetail frag is available, we're in two-pane
            // layout...

            listProduct.updateData();

        }

    }

    @Override
    public void onShowFullScreenVideo(boolean isFullScreen) {
        // TODO Auto-generated method stub
        ProductDetail productDetail = (ProductDetail)
                getSupportFragmentManager().findFragmentById(R.id.detail_fragment);
        Activity activity = getParent();
        OnMainActivityListener activityListener = (OnMainActivityListener) activity;
        activityListener.onShowHideTabWidget(!isFullScreen);
        if (isFullScreen) {
            findViewById(R.id.search_bar).setVisibility(View.GONE);
            findViewById(R.id.title).setVisibility(View.GONE);

            if (productDetail != null) {
                productDetail.hideDescription();
                findViewById(R.id.list_product_fragment).setVisibility(View.GONE);
            } else {
                ProductDetail detail = (ProductDetail)
                        getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                detail.hideDescription();

            }
        } else {
            findViewById(R.id.search_bar).setVisibility(View.VISIBLE);
            findViewById(R.id.title).setVisibility(View.VISIBLE);

            if (productDetail != null) {
                productDetail.showDescription();
                findViewById(R.id.list_product_fragment).setVisibility(View.VISIBLE);
            } else {
                ProductDetail detail = (ProductDetail)
                        getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                detail.showDescription();

            }

        }

    }
}
